# --coding:utf-8--
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import paho.mqtt.client as mqtt
from urllib import request
mqtt_ip = '140.143.18.81'
APP_ID = "cli_9f2c2c6d0bfa500b"
APP_SECRET = "o0Hv5tXLwy5HL5VWRB5oIhwEGZ2Lqvzc"
open_id = 'ou_4fe427b0fb668c5134568bbbba353a87'
chat_id = 'oc_09a9a1f03252fa13b5540341c995eebb'
def on_connect(client, userdata, rc, msg):
    client.subscribe('TemperatureTopic')
    # client.publish(topic2, "STARTING SERVER")

def on_message(client, userdata, msg):
    print(msg.topic + " " + ":" + str(msg.payload))
    tempMsg = str(msg.payload)
    tempMsg = tempMsg.replace('\'','')
    tempMsg = tempMsg.replace('b','')
    text = "室温："+ tempMsg.split(",")[0]+"℃" + "   湿度："+tempMsg.split(",")[1]+"%RH"
    # 调用发消息 API 之前，先要获取 API 调用凭证：tenant_access_token
    access_token = get_tenant_access_token()
    if access_token == "":
        return
    # 机器人 echo 收到的消息
    send_message(access_token, open_id, text)

def get_tenant_access_token():
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
    headers = {
        "Content-Type" : "application/json"
    }
    req_body = {
        "app_id": APP_ID,
        "app_secret": APP_SECRET
    }

    data = bytes(json.dumps(req_body), encoding='utf8')
    req = request.Request(url=url, data=data, headers=headers, method='POST')
    try:
        response = request.urlopen(req)
    except Exception as e:
        print(e.read().decode())
        return ""

    rsp_body = response.read().decode('utf-8')
    rsp_dict = json.loads(rsp_body)
    code = rsp_dict.get("code", -1)
    if code != 0:
        print("get tenant_access_token error, code =", code)
        return ""
    return rsp_dict.get("tenant_access_token", "")

def send_message(token, open_id, text):
    url = "https://open.feishu.cn/open-apis/message/v4/send/"

    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + token
    }
    req_body = {
        "open_id": open_id,
        "chat_id": chat_id,
        "msg_type": "text",
        "content": {
            "text": text
        }
    }

    data = bytes(json.dumps(req_body), encoding='utf8')
    req = request.Request(url=url, data=data, headers=headers, method='POST')
    try:
        response = request.urlopen(req)
    except Exception as e:
        print(e.read().decode())
        pass

    rsp_body = response.read().decode('utf-8')
    rsp_dict = json.loads(rsp_body)
    code = rsp_dict.get("code", -1)
    if code != 0:
        print("send message error, code = ", code, ", msg =", rsp_dict.get("msg", ""))
client = mqtt.Client(client_id="webServer02")
client.username_pw_set("iot_test", "bilibili")
client.on_connect = on_connect
client.on_message = on_message
# print('test')
client.connect(mqtt_ip)
client.loop_forever()